import { TokenService } from '~~/server/utils/tokens'
import { usersTable } from '~~/server/db/schema/user'
import { db } from '~~/server/db'
import { eq } from 'drizzle-orm'

export default defineEventHandler(async (event) => {
  const refreshToken = getCookie(event, 'refreshToken')

  if (!refreshToken) {
    throw createError({
      statusCode: 401,
      message: 'Refresh token not found'
    })
  }

  try {
    const storedToken = await TokenService.validateRefreshToken(refreshToken)
    if (!storedToken) {
      throw createError({
        statusCode: 401,
        message: 'Invalid refresh token'
      })
    }

    const payload = TokenService.verifyRefreshToken(refreshToken)

    const [user] = await db.select().from(usersTable).where(eq(usersTable.id, payload.id)).limit(1)

    if (!user) {
      throw createError({
        statusCode: 401,
        message: 'User not found'
      })
    }

    const newAccessToken = TokenService.generateAccessToken({
      id: user.id,
      phone: user.phone,
      role: user.role
    })

    setCookie(event, 'accessToken', newAccessToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 15 * 60,
      path: '/',
      sameSite: 'strict'
    })

    return {
      message: 'Token refreshed successfully',
      accessToken: newAccessToken
    }
  } catch (error: any) {
    deleteCookie(event, 'accessToken')
    deleteCookie(event, 'refreshToken')

    throw createError({
      statusCode: 401,
      message: 'Token refresh failed'
    })
  }
})
